import datetime
from re import S
import db
import KBEDebug as log
import KBEngine


class AdsInfo:
    def __init__(self, table_name):
        self.table_name = table_name
        self.tb = db.DBTable(table_name)
        # 日期
        self.tb.setFiled('date', db.UNICODE(10))
        # 今日玩家数
        self.tb.setFiled('adsCount', db.UINT32())

    def createTable(self, success_callback):
        self.tb.exec(success_callback)


class IAdsInfo:
    def __init__(self):
        self.tb_adsInfo = AdsInfo('lobby_ads_info')
        self.tb_create_count = 1
        self.tb_adsInfo.createTable(self.createTableSuccess)

        self.createTodayAdsRecord()

    def createTableSuccess(self):
        self.tb_create_count -= 1
        if self.tb_create_count <= 0:
            pass

    def updateTodayAdsCount(self):
        date_str = datetime.datetime.now().date().strftime('%Y-%m-%d')
        sql = f'UPDATE lobby_ads_info SET adsCount = adsCount + 1 WHERE date = \"{date_str}\"'
        log.DEBUG_MSG(f'update today ads record')
        KBEngine.executeRawDatabaseCommand(sql, None)

    def createTodayAdsRecord(self):
        date_str = datetime.datetime.now().date().strftime('%Y-%m-%d')

        def callback(record):
            if len(record) == 0:
                date_str = datetime.datetime.now().date().strftime('%Y-%m-%d')
                # 创建一条记录
                info = self.createAdsRecord(date_str)
                self.tb_adsInfo.tb.addLine(info)
                log.DEBUG_MSG(f'create today ads info')
            else:
                log.INFO_MSG(f'exist today ads record')
        self.tb_adsInfo.tb.loadAll(f'date=\"{date_str}\"', callback)
        pass

    def createAdsRecord(self, date_str):
        record = {
            'date': date_str,
            'adsCount': 0
        }
        return record
